﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Serialization;
using System.Xml;

namespace Ada.Protocol
{
	public class Config
	{

		#region Singleton Pattern

		private static readonly Config instance = new Config();
		
		//Force .net compiler to not apply beforefieldinit. That would be very naughty indeed.
		static Config()
		{
            if (!instance.Loaded)
                instance.Load();
		}

		Config()
		{
		}

		public static Config Instance
		{
			get
			{
				return instance;
			}
		}
		#endregion

		[XmlElement]
		public string nzbMatrixUsername { get; set; }
		[XmlElement]
		public string nzbMatrixApiKey { get; set; }

        [XmlElement]
        public string outputPath { get; set; }

		[XmlArray("Servers"), XmlArrayItem("Server", type:typeof(AdaNNTP.NNTPServer))]
		public List<AdaNNTP.NNTPServer> knownServers;

		[XmlIgnore]
		private string configFilePath = 
			Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + 
			Path.DirectorySeparatorChar.ToString() +
			"Ada" +
			Path.DirectorySeparatorChar.ToString();

        [XmlIgnore]
		public bool Loaded = false;

		public void Load()
		{
			if (!Loaded)
			{
				FileStream fs = new FileStream(configFilePath + "config.xml", FileMode.Open, FileAccess.Read);
				StreamReader sr = new StreamReader(fs);
				XmlTextReader xr = new XmlTextReader(sr);
				XmlSerializer xs = new XmlSerializer(this.GetType());
				object c;
				if (xs.CanDeserialize(xr))
				{
					c = xs.Deserialize(xr);
                    
					this.nzbMatrixApiKey = ((Config)c).nzbMatrixApiKey;
					this.nzbMatrixUsername = ((Config)c).nzbMatrixUsername;
					this.knownServers = ((Config)c).knownServers;
                    this.outputPath = ((Config)c).outputPath;
				}
				xr.Close();
				sr.Close();
                fs.Close();
			}
			Loaded = true;
		}

		public void Save()
		{
			Loaded = true;
			FileStream fs = null;
			StreamWriter w = null;
			XmlSerializer s;
            try
            {
                fs = new FileStream(configFilePath + "config.xml", FileMode.Create, FileAccess.Write);
                w = new StreamWriter(fs);
                s = new XmlSerializer(this.GetType());
                s.Serialize(w, this);
                w.Flush();
                fs.Flush();
            }
            catch
            {
                //The most likely error is that the directory is missing.
                Directory.CreateDirectory(configFilePath);
            }
		}
	}
}